package controllers;

import com.google.gson.JsonObject;
import constants.Configurations;
import constants.Default;
import constants.TplPath;
import constants.system.MemberShip;
import constants.ws.PageBean;
import duppentity.dto.sys.SysDtoUtil;
import duppentity.dto.sys.SysItemDto;
import utils.JsonUtils;
import utils.Utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ItemController extends  ApiController{


    /**
     * 菜单项列表
     */
    public static void itemList(){
        String page = TplPath.itemList;
        String dataJson = ItemController.getDataJson();
        if (Utils.exitFile(page)){
            renderTemplate(page,dataJson);
        }
    }


    /**
     * 生成layui  tree.js需要的json格式
     * @return
     */
    public static String getDataJson() {
        JsonObject data = itemDupp.getItemList(0,Integer.MAX_VALUE);
        if (!checkResult(data)) {
            apiError(data);
        }
        List<SysItemDto> sysItemDtoList = SysDtoUtil.getSysItemListDto(data);
        //排序
        Collections.sort(sysItemDtoList, new Comparator<SysItemDto>() {
            @Override
            public int compare(SysItemDto o1, SysItemDto o2) {
                return o1.sequence.compareTo(o2.sequence);
            }
        });

        List<JsonObject> zeroList = new ArrayList<>();
        List<JsonObject> oneList = new ArrayList<>();
        List<JsonObject> twoList = new ArrayList<>();
        if (sysItemDtoList.size() > 0) {
            for (Integer i = 0; i < sysItemDtoList.size(); i++) {
                SysItemDto itemDto = sysItemDtoList.get(i);
                JsonObject tmp = new JsonObject();
                if (itemDto.level.equals(Default.itemLevel.zero)) {
                    tmp.addProperty("id", itemDto.id);
                    tmp.addProperty("title", itemDto.name);
                    zeroList.add(tmp);
                } else if (itemDto.level.equals(Default.itemLevel.one)) {
                    tmp.addProperty("id", itemDto.id);
                    tmp.addProperty("parentId", itemDto.parentId);
                    tmp.addProperty("title", itemDto.name);
                    oneList.add(tmp);
                } else if (itemDto.level.equals(Default.itemLevel.two)) {
                    tmp.addProperty("id", itemDto.id);
                    tmp.addProperty("parentId", itemDto.parentId);
                    tmp.addProperty("title", itemDto.name);
                    twoList.add(tmp);
                }
            }
        }

        for (Integer a = 0; a < zeroList.size(); a++) {
            //顶级
            JsonObject aJson = zeroList.get(a).getAsJsonObject();
            List<JsonObject> oneContents = new ArrayList<>();
            for (Integer b = 0; b < oneList.size(); b++) {

                JsonObject bJson = oneList.get(b).getAsJsonObject();
                if (bJson.get("parentId").getAsLong() == aJson.get("id").getAsLong()) {
                    JsonObject content1 = new JsonObject();
                    content1.addProperty("id", bJson.get("id").getAsString());
                    content1.addProperty("title", bJson.get("title").getAsString());
                    //content1.addProperty("spread",Boolean.TRUE);

                    List<JsonObject> twoContents = new ArrayList<>();
                    for (Integer c = 0; c < twoList.size(); c++) {
                        JsonObject cJson = twoList.get(c).getAsJsonObject();
                        if (cJson.get("parentId").getAsLong() == bJson.get("id").getAsLong()) {
                            JsonObject content2 = new JsonObject();
                            content2.addProperty("id", cJson.get("id").getAsString());
                            content2.addProperty("title", cJson.get("title").getAsString());
                            //content2.addProperty("spread",Boolean.TRUE);
                            content2.addProperty("level", Default.itemLevel.two);
                            twoContents.add(content2);
                        }
                    }
                    content1.add("children", JsonUtils.toJsonTree(twoContents));
                    content1.addProperty("spread", Boolean.TRUE);
                    content1.addProperty("level", Default.itemLevel.one);
                    oneContents.add(content1);
                }
                aJson.addProperty("spread", Boolean.TRUE);
                aJson.addProperty("level", Default.itemLevel.zero);
                aJson.add("children", JsonUtils.toJsonTree(oneContents));
            }
        }
        String dataJson = JsonUtils.formatJson(zeroList).replaceAll("\"(\\w+)\"(\\s*:\\s*)", "$1$2");
        return  dataJson;
    }

    public static void getItemList() {
        JsonObject data = itemDupp.getItemList(0,Integer.MAX_VALUE);
        if (!checkResult(data)) {
            apiError(data);
        }
        List<SysItemDto> sysItemDtoList = SysDtoUtil.getSysItemListDto(data);
        apiList(data, sysItemDtoList);
    }



    public static void getItem(){
        String page = TplPath.editItem;
        Long id = params.get("id",Long.class);
        JsonObject result = null;
        if (id>0) {
            result =itemDupp.getItem(id);
        }
        if (result!=null) {
            SysItemDto roleDto = SysDtoUtil.getSysItemDto(result);
            apiList(result,roleDto);
        }
    }

    /**
     * 保存菜单
     */
    public static void saveItem(){
        Long id = params.get("id",Long.class);

        Long parentId = params.get("parentId",Long.class);
        Integer level = params.get("level",Integer.class);

        String style = params.get("style",String.class);
        Integer sequence = params.get("sequence",Integer.class);

        String name = params.get("name",String.class);
        String itemHref = params.get("itemHref",String.class);
        if (level.equals(Default.itemLevel.zero)){
            if (Utils.isNullOrEmpty(style)){
                apiError("请填写菜单样式");
            }
            if (!Utils.isNullOrEmpty(itemHref)){
                apiError("不用填写地址");
            }
            if (parentId>0){
                apiError("父ID请填写为0");
            }
        }else if(level.equals(Default.itemLevel.one) || level.equals(Default.itemLevel.two)){
            if (!Utils.isNullOrEmpty(style)){
                apiError("不用填写菜单样式");
            }
            if (Utils.isNullOrEmpty(itemHref)){
                apiError("请填写地址");
            }
            if (parentId==0){
                apiError("父ID不能为0");
            }
        }

        MemberShip memberShip = MemberShip.current();
        if (id!=null && id > 0) {
            JsonObject data = itemDupp.editItem(memberShip.getSessionId(),memberShip.getId(),id,parentId,level,name,style,sequence,itemHref,MemberShip.current().getId());
            if (checkResult(data)) {
                if (data.get("result").getAsBoolean()) {
                    apiOk("修改菜单成功");
                } else {
                    apiError("修改菜单失败");
                }
            } else {
                apiError(data);
            }
        } else {
            JsonObject data = itemDupp.addItem(memberShip.getSessionId(),memberShip.getId(),parentId,level,name,style,sequence,itemHref,MemberShip.current().getId());
            if (checkResult(data)) {
                Long itemId = data.get("id").getAsLong();
                if (itemId > 0) {
                    String userRoleIds = memberShip.getUserRoleIds();
                    String superAdminRoleIds = Configurations.superAdminRoleIds;
                    List<String> resultIds = Utils.compareString(userRoleIds,superAdminRoleIds);
                    if (resultIds.size()>0){
                        for (Integer i=0;i<resultIds.size();i++){
                            String roleId = resultIds.get(i);
                            itemDupp.addRoleItem(memberShip.getSessionId(), memberShip.getId(),itemId,Long.parseLong(roleId),memberShip.getId());
                        }
                    }
                    apiOk("保存菜单成功");
                } else {
                    apiError("保存菜单失败");
                }
            } else {
                apiError(data);
            }
        }
    }


    public static void deleteItem() {
        String ids= params.get("id", String.class);
        if (Utils.isNullOrEmpty(ids)){
            apiError("没有选择菜单删除");
        }
        String[] strIds = ids.split(",");
        Integer number =0;
        if (strIds.length>0){
            for (Integer i=0;i<strIds.length;i++){
                Long id = Long.parseLong(strIds[i]);
               JsonObject data= itemDupp.deleteItem(id, MemberShip.current().getId());
                if (checkResult(data)) {
                    if (data.get("result").getAsBoolean()) {
                        number=number+1;
                    }
                }
            }
        }

        if (number.equals(strIds.length)){
            apiOk("删除菜单成功");
        } else {
            apiError("删除菜单失败");
        }
    }
}
